//
//  QQAipOcrManager.m
//  QQZF
//
//  Created by hdz on 2018/6/4.
//  Copyright © 2018年 com.szqqkj. All rights reserved.
//

#import "QQAipOcrManager.h"
#import <AipOcrSdk/AipOcrSdk.h>
#import <UIKit/UIKit.h>


@interface QQAipOcrManager ()

@property (copy, nonatomic) void(^succes)(NSDictionary *model);

@property (copy, nonatomic) void(^bankImage)(UIImage *image);

@property (copy, nonatomic) void(^userInfoBack)(NSDictionary *dict);

@end

@implementation QQAipOcrManager{
    // 默认的识别成功的回调
    void (^_successHandler)(id);
    // 默认的识别失败的回调
    void (^_failHandler)(NSError *);
    
}


- (void)configSettings {
    NSString *licenseFile = [[NSBundle mainBundle] pathForResource:@"aip" ofType:@"license"];
    NSData *licenseFileData = [NSData dataWithContentsOfFile:licenseFile];
    [[AipOcrService shardService] authWithLicenseFileData:licenseFileData];
    [self configCallback];
}

- (void)callBack:(void (^)(NSDictionary *))back {
    _succes = ^(NSDictionary *dict) {
        if (back) {
            back(dict);
        }
    };
}


- (void)imgBack:(void (^)(UIImage *))img {
    _bankImage = ^(UIImage *image) {
        if (img) {
            img(image);
        }
    };
}

- (void)callBackIdcard:(void (^)(NSDictionary *))back {
    _userInfoBack = ^(NSDictionary *dict) {
        if (back) {
            back(dict);
        }
    };
}

- (void)begainwithType:(QQAipOcrManagerType)type {
    _ocrType = type;
    CardType cardType = type == QQAipOcrManagerTypeIdCardFont ? CardTypeIdCardFont : CardTypeIdCardBack;
    WS(weakSelf)
    UIViewController * vc =
    [AipCaptureCardVC ViewControllerWithCardType:cardType
                                 andImageHandler:^(UIImage *image) {
                                     
                                     if (type == QQAipOcrManagerTypeIdCardFont) {
                                         [[AipOcrService shardService] detectIdCardFrontFromImage:image    withOptions:nil successHandler:_successHandler                                                                             failHandler:_failHandler];
                                     } else if (type == QQAipOcrManagerTypeIdCardBank) {
                                         [[AipOcrService shardService] detectIdCardBackFromImage:image withOptions:nil successHandler:_successHandler failHandler:_failHandler];
                                     } else {
                                         [[AipOcrService shardService] detectBankCardFromImage:image
                                                                                successHandler:_successHandler failHandler:_failHandler];
                                     }
                                     if (_bankImage) {
                                         weakSelf.bankImage(image);
                                     }
                                 }];
    [[Utility currentViewController] presentViewController:vc animated:YES completion:nil];
}


- (void)configCallback {
    WS(weakSelf)
    // 这是默认的识别成功的回调
    _successHandler = ^(id result){
        NSDictionary* dic = [result objectForKey:@"words_result"];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (_ocrType == QQAipOcrManagerTypeBank) {
                weakSelf.succes(dic);
            } else if (_ocrType == QQAipOcrManagerTypeIdCardFont) {
                NSString *name = dic[@"姓名"][@"words"];
                NSString *cardNum = dic[@"公民身份号码"][@"words"];
                NSString *address = dic[@"住址"][@"words"];
                
                NSDictionary *dict = @{
                                       @"name" :kisStrNiL(name),
                                       @"cardNum": kisStrNiL(cardNum),
                                       @"address": kisStrNiL(address)
                                       };
                weakSelf.userInfoBack(dict);
            }
                    
            [[Utility currentViewController] dismissViewControllerAnimated:YES completion:nil];
        });
        
    };
    _failHandler = ^(NSError *error){
        NSLog(@"%@", error);
        NSString *msg = [NSString stringWithFormat:@"%li:%@", (long)[error code], [error localizedDescription]];
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            LEEAlert.alert.config.LeeTitle(@"识别失败").LeeContent(msg).LeeCancelAction(@"确定", ^{
                [[Utility currentViewController] dismissViewControllerAnimated:YES completion:nil];
            }).LeeShow();
        }];
    };
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        
        [self configSettings];
    }
    return self;
}

static QQAipOcrManager *_instance = nil;

+ (instancetype)shareOCR {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

@end
